/**

 @Name：layuiAdmin 核心模块
 @Author：贤心
 @Site：http://www.layui.com/admin/
 @License：LPPL
    
 */

layui.define('view', function (exports) {
  var $ = layui.jquery,
    laytpl = layui.laytpl,
    element = layui.element,
    setter = layui.setter,
    view = layui.view,
    device = layui.device()

    ,
    $win = $(window),
    $body = $('body'),
    container = $('#' + setter.container)

    ,
    SHOW = 'layui-show',
    HIDE = 'layui-hide',
    THIS = 'layui-this',
    DISABLED = 'layui-disabled',
    TEMP = 'template',
    APP_BODY = '#LAY_app_body',
    APP_FLEXIBLE = 'LAY_app_flexible',
    FILTER_TAB_TBAS = 'layadmin-layout-tabs',
    APP_SPREAD_SM = 'layadmin-side-spread-sm',
    TABS_BODY = 'layadmin-tabsbody-item',
    ICON_SHRINK = 'layui-icon-shrink-right',
    ICON_SPREAD = 'layui-icon-spread-left',
    SIDE_SHRINK = 'layadmin-side-shrink',
    SIDE_MENU = 'LAY-system-side-menu'

    //通用方法
    ,
    admin = {
      //v: '1.2.1 pro'
      v: layui.cache.version,
      lang: view.lang()

        //数据的异步请求
        ,
      req: view.req
        //清除本地 token，并跳转到登入页
        ,
      exit: view.exit

        //xss 转义
        ,
      escape: function (html) {
        return String(html || '').replace(/&(?!#?[a-zA-Z0-9]+;)/g, '&amp;')
          .replace(/</g, '&lt;').replace(/>/g, '&gt;')
          .replace(/'/g, '&#39;').replace(/"/g, '&quot;');
      },
      trimAll: function (str) {
        //去除所有空格
        if (str !== undefined && typeof str === 'string')
          return str.replace(/\s/g, '');
        else
          return str;
      },
      number_format: function (number, decimals, dec_point, thousands_sep) {
        /*
         * 参数说明：
         * number：要格式化的数字
         * decimals：保留几位小数
         * dec_point：小数点符号
         * thousands_sep：千分位符号
         * */
        number = (number + '').replace(/[^0-9+-Ee.]/g, '');
        var n = !isFinite(+number) ? 0 : +number,
          prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
          sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
          dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
          s = '',
          toFixedFix = function (n, prec) {
            var k = Math.pow(10, prec);
            return '' + Math.ceil(n * k) / k;
          };
        s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
        var re = /(-?\d+)(\d{3})/;
        while (re.test(s[0])) {
          s[0] = s[0].replace(re, "$1" + sep + "$2");
        }
        if ((s[1] || '').length < prec) {
          s[1] = s[1] || '';
          s[1] += new Array(prec - s[1].length + 1).join('0');
        }
        return s.join(dec);
      },
      trimArray: function (arrStr) {
        var arr = admin.trimAll(arrStr).split(',');
        var temp = [];
        $.each(arr, function (k, v) {
          if (v !== '' && $.inArray(v, temp) === -1)
            temp.push(v);
        });
        return temp;
        //$.unique(arr.sort());
        //arr = arr.filter(s => $.trim(s).length > 0);
        //return arr;
      },
      getyear: function () {
        var yearArr = [];
        var myDate = new Date();
        nowYear = myDate.getFullYear(); //当前年
        var endYear = nowYear;
        var startYear = nowYear - 3;
        for (var int = startYear; int <= endYear; int++) {
          yearArr.push(int);
        }
        return yearArr
      },
      getmonth: function (year) {

        var monthArr = [];
        var myDate = new Date();
        nowYear = myDate.getFullYear(); //当前年
        var nowMonth;
        if (year == nowYear) {
          nowMonth = myDate.getMonth() + 1;
        } else {
          nowMonth = 12
        }
        var startMonth = 1;
        for (var int = startMonth; int <= nowMonth; int++) {


          monthArr.push(('0' + int).substring(('0' + int).length - 2));
        }
        return monthArr
      },
      getday: function (year, month) {

        var dayArry = [];
        var d = new Date(year, month, 0);

        for (var i = 1; i <= d.getDate(); i++) {
          dayArry.push(('0' + i).substring(('0' + i).length - 2));
        }
        return dayArry;
      },
      optionsArray: function (arrStr) {
        var arr = arrStr.replace(/[\r\n]/g, '').replace(/[\n]/g, '').split(','); //admin.trimAll(arrStr)
        var temp = [];
        $.each(arr, function (k, v) {
          if (v !== '' && $.inArray(v, temp) === -1)
            temp.push(v);
        });
        return temp;
        //$.unique(arr.sort());
        //arr = arr.filter(s => $.trim(s).length > 0);
        //return arr;
      },
      trimCodeAll: function (str) {
        //去除所有空格
        if (str !== undefined && typeof str === 'string')
          return str.replace(/\s/g, '').replace(/&nbsp;/g, '');
        else
          return str;
      },
      getURLParams: function (url) {
        var result = {};
        var reg = new RegExp('([\?|&])(.+?)=([^&?]*)', 'ig');
        var arr = reg.exec(url);

        while (arr) {
          result[arr[2]] = arr[3];

          arr = reg.exec(url);
        }

        return result;
      },
      changeURLArg: function (url, arg, arg_val) {

        var pattern = arg + '=([^&]*)';
        var replaceText = arg + '=' + arg_val;
        if (url.match(pattern)) {
          var tmp = '/(' + arg + '=)([^&]*)/gi';
          tmp = url.replace(eval(tmp), replaceText);
          return tmp;
        } else {
          if (url.match('[\?]')) {
            return url + '&' + replaceText;
          } else {
            return url + '?' + replaceText;
          }
        }
      },
      uuid: function uuid(len, radix) {
          //uuid
          var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
          var uuid = [],
            i;
          radix = radix || chars.length;

          if (len) {
            for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix];
          } else {
            var r;

            uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
            uuid[14] = '4';

            for (i = 0; i < 36; i++) {
              if (!uuid[i]) {
                r = 0 | Math.random() * 16;
                uuid[i] = chars[(i === 19) ? (r & 0x3) | 0x8 : r];
              }
            }
          }

          return uuid.join('');
        }

        //样式处理
        ,
      replaceClass: function (elem, oldClass, newClass) {

          if ($.isArray(oldClass))
            $.each(oldClass, function (k, v) {
              $(elem).removeClass(v);
            });
          else
            $(elem).removeClass(oldClass);

          if ($.isArray(newClass))
            $.each(newClass, function (k, v) {
              $(elem).addClass(v);
            });
          else
            $(elem).addClass(newClass);
        }

        //格式化
        ,
      decimal: function (num, v) {
        var vv = Math.pow(10, v);
        return admin.formatNum(Math.round(num * vv) / vv);
      },
      formatNum: function (strNum) {
          return (strNum + '').replace(/\d{1,3}(?=(\d{3})+(\.\d*)?$)/g, '$&,');
        }

        ,
      timeFormat_YMD: function (v) {
        return admin.getYMDHMS(v).substr(0, 10);
      },
      timeFormat_YMDH: function (v) {
        return admin.getYMDHMS(v).substr(0, 13);
      },
      timeFormat_YMDHM: function (v) {
        return admin.getYMDHMS(v).substr(0, 16);
      },
      timeFormat_YMDHMS: function (v) {
        return admin.getYMDHMS(v).substr(0, 19);
      },
      getYMDHMS: function (time) {
        if (!time) return '';
        var date = '';

        if (!/Invalid|NaN/.test(new Date(time))) {
          date = new Date(time);
        } else if (time.indexOf('/Date') > -1) {

          time = time.substr(1, time.length - 2);
          var obj = admin.evalObj("{Date: new " + time + "}");
          date = obj["Date"];
        } else {
          time = time.replace(/-/g, ':').replace(' ', ':');
          time = time.split(':');
          date = new Date(time[0], (time[1] - 1), time[2], time[3], time[4], time[5]);
        }

        var year = date.getFullYear();
        var month = date.getMonth() + 1;
        var day = date.getDate();
        month = month < 10 ? '0' + month : month;
        day = day < 10 ? '0' + day : day;

        var YMD = year + '-' + month + '-' + day;

        var hours = date.getHours();
        var minutes = date.getMinutes();
        var seconds = date.getSeconds();

        hours = hours < 10 ? '0' + hours : hours;
        minutes = minutes < 10 ? '0' + minutes : minutes;
        seconds = seconds < 10 ? '0' + seconds : seconds;

        var HMS = hours + ':' + minutes + ':' + seconds;
        //+ '.' + date.getMilliseconds()

        return YMD + ' ' + HMS;
      },
      getExcelDate: function (datetime) {
        if (!isNaN(datetime)) {
          let time = new Date((datetime - 1) * 24 * 60 * 60 * 1000);

          time.setYear(time.getFullYear() - 70);
          time.setHours(time.getHours() - 8);
          return admin.getYMDHMS(time);
        } else
          return datetime;
      },
      cellTemplet: function (fun, val) {
          return eval('admin.' + fun + '(val)'); //admin.funObj('admin.' + fun,val);
        }

        ,
      hasArray: function (data) {
        return $.isArray(data) && data.length > 0;
      },
      hasObject: function (data) {
        return $.isPlainObject(data) && !$.isEmptyObject(data);
      },
      jsonClone: function (data) {
        return JSON.parse(JSON.stringify(data));
      },
      stringify: function (obj) {
        return JSON.stringify(obj, function (key, val) {
          if (typeof val === 'function') {
            return val + '';
          }
          return val;
        });
      },
      parse: function (str) {
        return JSON.parse(str, function (k, v) {
          if (v.indexOf && v.indexOf('function') > -1) {
            return eval("(function(){return " + v + " })()");
          }
          return v;
        });
      },
      stringToObj: function (str) {
        return admin.parse(JSON.stringify(str));
      },
      evalObj: function (v) {
        return eval('(' + v + ')');
      },
      funObj: function (json, params) {
          return (new Function("params", "return " + json))(params);
        }

        //字段不一致报错，用sortBy
        ,
      jsonSort: function (array, field, reverse) {
        //数组长度小于2 或 没有指定排序字段 或 不是json格式数据
        if (array.length < 2 || !field || typeof array[0] !== "object") return array;
        //数字类型排序
        if (typeof array[0][field] === "number") {
          array.sort(function (x, y) {
            return x[field] - y[field];
          });
        }
        //字符串类型排序
        if (typeof array[0][field] === "string") {
          array.sort(function (x, y) {
            return x[field].localeCompare(y[field]);
          });
        }
        //倒序
        if (reverse) {
          array.reverse();
        }
        return array;
      },
      sortBy: function (filed, rev, primer) {
        rev = (rev) ? -1 : 1;
        return function (a, b) {
          a = a[filed];
          b = b[filed];
          if (primer && typeof (primer) !== 'undefined') {
            a = primer(a);
            b = primer(b);
          } else {
            if (!isNaN(a) && !isNaN(a)) {
              a = Number(a);
              b = Number(b);
            }
          }
          if (a < b) {
            return rev * -1;
          }
          if (a > b) {
            return rev * 1;
          }
          return 1;
        };
      },
      jsonData: function (url, callback) {
        $.getJSON(url + '.json?v=' + admin.v, '', function (data) {
          callback(data);
        });
      },
      localData: function (key, options) {
        var local = layui.data(setter.tableName);

        local[key] = options;

        layui.data(setter.tableName, {
          key: key,
          value: local[key]
        });
      },
      getLocalData: function (key) {
        var local = layui.data(setter.tableName);

        local[key] = local[key] || undefined;

        return local[key];
      },
      sessionData: function (options) {
        var local = layui.sessionData(setter.tableName);

        local.dataset = local.dataset || {};

        layui.each(options, function (key, value) {
          local.dataset[key] = value;
        });

        layui.sessionData(setter.tableName, {
          key: 'dataset',
          value: local.dataset
        });
      },
      removeSessionData: function (key) {
        var local = layui.sessionData(setter.tableName);

        local.dataset = local.dataset || {};

        local.dataset[key] = null;

        layui.sessionData(setter.tableName, {
          key: 'dataset',
          value: local.dataset
        });
      },
      clearSessionData: function () {
        layui.sessionData(setter.tableName, {
          key: 'dataset',
          value: null
        });
      },
      getSessionList: function (list) {
          var local = layui.sessionData(setter.tableName);

          local.dataset = local.dataset || {};

          return local.dataset[list];
        }

        ,
      getDictionary: function (type, table, callback) {
        var list = admin.getSessionList(type + '-' + table);
        debugger;
        if (admin.hasArray(list)) {
          typeof callback === 'function' && callback(admin.jsonClone(list));
        } else {
          admin.req({
            url: '/Admin/getDictionarySelect',
            type: 'post',
            data: {
              Order: 'OrderNo',
              SearchWhere: JSON.stringify([{
                searchValue: type,
                compare: 'Type',
                condition: '='
              }, {
                searchValue: table,
                compare: 'ParentType',
                condition: '='
              }])
            },
            loading: false,
            tipOk: false,
            done: function (res) {
              if (res.data && res.data.length > 0) {
                var setTable = {};
                setTable[type + '-' + table] = res.data;
                admin.sessionData(setTable);
              }
              typeof callback === 'function' && callback.call(this, res.data);
            }
          });
        }
      },
      filterList: function (jsonList, where) {
        var tempArray = [];
        //debugger;

        var index = 0;
        $.each(where, function (k, v) {
          index++;
          if ($.isArray(v))
            $.each(v, function (ak, av) {
              $.each(jsonList, function (idx, json) {
                if (json[k] + '' === av + '') {
                  tempArray.push(json);
                }
              });
            });
          else
            $.each(jsonList, function (idx, json) {
              if (json[k] + '' === v + '') {
                tempArray.push(json);
              }
            });

          if (tempArray.length === 0)
            return false;

          if (index < Object.keys(where).length) {
            if (tempArray.length > 0) {
              jsonList = JSON.parse(JSON.stringify(tempArray));
              tempArray = [];
            }
          }
        });
        return tempArray;
      },
      updateJsonListObjIndex: function (jsonList, oldJson, oldItemId, newItemId, moveStep) {
        //更新集合对象位置
        $.each(jsonList, function (idx, json) {
          if (json.itemId === newItemId) {
            jsonList.splice(idx + moveStep, 0, admin.jsonClone(oldJson));
            return false;
          }
          if (json.array) {
            admin.updateJsonListObjIndex(json.array, oldJson, oldItemId, newItemId, moveStep);
          }
        });
      },
      updateJsonListObjByItemId: function (jsonList, jsonObj, itemId) {
        //更新集合对象
        $.each(jsonList, function (idx, json) {
          if (json.itemId === itemId) {
            jsonList.splice(idx, 1, admin.jsonClone(jsonObj));
            return false;
          }
          if (json.array) {
            admin.updateJsonListObjByItemId(json.array, jsonObj, itemId);
          }
        });
      },
      getJsonObjFromListByItemId: function (jsonList, itemId) {
        //根据itemId获取集合数据
        var jsonObj = null;
        var array = [];
        $.each(jsonList, function (idx, json) {
          if (json.itemId === itemId) {
            jsonObj = admin.jsonClone(json);
            return;
          }
          if (json.array) {
            $.each(json.array, function (cidx, cjson) {
              array.push(cjson);
            });
          }
        });
        if (jsonObj === null && array.length > 0)
          return admin.getJsonObjFromListByItemId(array, itemId);
        else
          array = null;
        return jsonObj;
      },
      getJsonObjFromListByKey: function (jsonList, key, val) {
        var jsonObj = null;
        var array = [];
        $.each(jsonList, function (idx, json) {
          if (json.key === val) {
            jsonObj = admin.jsonClone(json);
            return;
          }
          if (json.array) {
            $.each(json.array, function (cidx, cjson) {
              array.push(cjson);
            });
          }
        });
        if (jsonObj === null && array.length > 0)
          return admin.getJsonObjFromListByItemId(array, itemId);
        else
          array = null;
        return jsonObj;
      },
      delJsonListObjByItemId: function (jsonList, itemId) {
          //根据itemId删除集合数据
          $.each(jsonList, function (idx, json) {
            if (json && json.itemId === itemId) {
              jsonList.splice(idx, 1);
              return false;
            }
            if (json.array) {
              admin.delJsonListObjByItemId(json.array, itemId);
            }
          });
        }

        ,
      initSessionData: function () {
          debugger
          admin.req({
            url: '/Admin/getDictionarySelect',
            type: 'post',
            data: {
              Order: 'Member',
              SearchWhere: JSON.stringify([{
                searchValue: 'page-form-field,page-table-cell,data-params,response-code,custom-params',
                compare: 'Type',
                condition: 'inchar'
              }])
            },
            loading: false,
            tipOk: false,
            success: function (res) {
              if (res.data && res.data.length > 0) {

                var dataSet = admin.filterList(res.data, {
                  ParentType: ['page-form-field', 'page-table-cell', 'data-params', 'response-code', 'custom-params']
                });
                if (dataSet.length > 0)
                  $.each(dataSet, function (idx, item) {
                    var list = admin.filterList(res.data, {
                      Type: item.Type,
                      ParentType: item.Member
                    });
                    if (list.length > 0) {
                      var setTable = {};
                      setTable[item.Type + '-' + item.Member] = list;
                      admin.sessionData(setTable);
                    }
                  });
              }
            }
          });
        }

        ,
      getDicParams: function (table, call) {
        var arr = table.split('-');

        admin.getDictionary(arr.slice(0, 2).join('-'), arr.slice(2).join('-'), call);
      },
      getDicParamsMember: function (table, key) {
        var item = admin.filterList(admin.getSessionList(table), {
          Member: key + ''
        })[0];
        return item ? item['MemberName' + admin.lang] : key;
      },
      updateDicParams: function (table) {
          var arr = table.split('-');
          admin.req({
            url: '/Admin/getDictionarySelect',
            type: 'post',
            data: {
              Order: 'OrderNo',
              SearchWhere: JSON.stringify([{
                searchValue: arr.slice(0, 2).join('-'),
                compare: 'Type',
                condition: '='
              }, {
                searchValue: arr.slice(2).join('-'),
                compare: 'ParentType',
                condition: '='
              }])
            },
            loading: false,
            tipOk: false,
            success: function (res) {
              if (res.data && res.data.length > 0) {
                var setTable = {};
                setTable[table] = res.data;
                admin.sessionData(setTable);
              }
            }
          });
        }

        ,
      getDataParams: function (table, call) {
        admin.getDictionary('data-params', table, call);
      },
      getDataParamsMember: function (table, key) {
        var item = admin.filterList(admin.getSessionList('data-params-' + table), {
          Member: key + ''
        })[0];
        return item ? item['MemberName' + admin.lang] : key;
      },
      updateDataParams: function (table) {
          admin.req({
            url: '/Admin/getDictionarySelect',
            type: 'post',
            data: {
              Order: 'OrderNo',
              SearchWhere: JSON.stringify([{
                searchValue: 'data-params',
                compare: 'Type',
                condition: '='
              }, {
                searchValue: table,
                compare: 'ParentType',
                condition: '='
              }])
            },
            loading: false,
            tipOk: false,
            success: function (res) {
              if (res.data && res.data.length > 0) {
                var setTable = {};
                setTable['data-params-' + table] = res.data;
                admin.sessionData(setTable);
              }
            }
          });
        }

        ,
      getCustomParams: function (table, call) {
        admin.getDictionary('custom-params', table, call);
      },
      getCustomParamsMember: function (table, key) {
        var item = admin.filterList(admin.getSessionList('custom-params-' + table), {
          Member: key + ''
        })[0];
        return item ? item['MemberName' + admin.lang] : key;
      },
      getCodeMsg: function (url, code) {
          var field = admin.filterList(admin.getSessionList('response-code-' + url), {
            Member: code + ''
          })[0];
          return field ? field['MemberName' + admin.lang] : null;
        }

        ,
      getPageSignById: function (pageId) {
        var obj = admin.filterList(admin.getSessionList('page'), {
          PageID: pageId
        })[0];
        return obj ? obj['Sign'] : '';
      },
      getPageSign: function () {
        if (layui.router().search.pageId) {
          var obj = admin.filterList(admin.getSessionList('page'), {
            PageID: layui.router().search.pageId
          })[0];
          return obj ? obj['Sign'] : '';
        } else
          return '';
      },
      getPageAreas: function () {
        var list = [];
        if (layui.router().search.pageId)
          list = admin.filterList(admin.getSessionList('page'), {
            ParentID: layui.router().search.pageId,
            PageType: 'area'
          });
        else if (layui.router().search.pageSign) {

          var menu = admin.filterList(admin.getSessionList('page'), {
            Sign: layui.router().search.pageSign,
            PageType: 'menu'
          }); //先通过菜单sign 找到对象
          if (menu.length === 1)
            list = admin.filterList(admin.getSessionList('page'), {
              ParentID: menu[0].PageID,
              PageType: 'area'
            });
        }
        return list || [];
      },
      getTabTitle: function (url) {
        var where = $.inArray(url, layui.setter.templatePage) > -1 ? {
          TemplateUrl: url,
          PageID: layui.router().search.pageId
        } : {
          PageUrl: url
        };

        var obj = admin.filterList(admin.getSessionList('page'), where)[0];
        return obj ? obj['PageName' + admin.lang] : (decodeURI(layui.router().search.tabTitle) || '');
      },
      getTableTitle: function (table) {
          var obj = admin.filterList(admin.getSessionList('page'), {
            Sign: table
          })[0];
          return obj ? obj['PageName' + admin.lang] : '';
        }

        ,
      tableCell: function (tableId, call) {
        admin.getDictionary('page-table-cell', tableId, call);
      },
      operationCell: view.lang() ? 'Operation' : '操作'

        ,
      getPageToolBtn: function (sign, where) {
        var page = admin.getSessionList('page');
        var item = admin.filterList(page, {
          Sign: sign
        })[0];

        var html = '';
        if (item)
          $.each(admin.filterList(page, $.extend(where, {
            ParentID: item.PageID,
            PageType: 'action'
          })), function (idx, data) {

            html += '<button class="layui-btn layuiadmin-btn-admin' + (data.Sign === 'batchdel' ? ' layui-btn-danger' : ' layui-btn-default') + '" type="button"  lay-event="' + data.Sign + '">' + data['PageName' + admin.lang] + '</button> ';
          });
        return html;
      },
      getPageToolbarBtn: function (sign, where) {
        var page = admin.getSessionList('page');
        var item = admin.filterList(page, {
          Sign: sign
        })[0];
        var html = '';
        if (item)
          $.each(admin.filterList(page, $.extend(where, {
            ParentID: item.PageID,
            PageType: 'cellAction'
          })), function (idx, data) {
            html += '<button class="layui-btn layui-btn-xs' + (data.Sign === 'del' ? ' layui-btn-danger' : ' layui-btn-default') + '" lay-event="' + data.Sign + '">' + (data.PageIcon ? '<i class="layui-icon ' + data.PageIcon + '"></i>' : data['PageName' + admin.lang]) + '</button> ';
          });
        return html;

        //var page = admin.getSessionList('page');

        //var item = admin.filterList(page, { Sign: sign })[0];

        //var pageToolbar = admin.getSessionList(sign + '-Toolbar');
        //if (!pageToolbar) {
        //    pageToolbar = admin.filterList(page, { ParentID: item.PageID, PageType: 'cellAction' });
        //    var setDate = {};
        //    setDate[sign + '-Toolbar'] = pageToolbar;
        //    admin.sessionData(setDate);
        //}
        //var html = '';
        //if (item)
        //    $.each(admin.filterList(pageToolbar, where), function (idx, data) {
        //        html += '<button class="layui-btn layui-btn-xs' + (data.Sign === 'del' ? ' layui-btn-danger' : ' layui-btn-default') + '" lay-event="' + data.Sign + '">' + (data.PageIcon ? '<i class="layui-icon ' + data.PageIcon + '"></i>' : data['PageName' + admin.lang]) + '</button> ';
        //    });
        //return html;
      },
      getFormBtn: function (sign, where) {
        var page = admin.getSessionList('page');
        var item = admin.filterList(page, {
          Sign: sign
        })[0];

        var html = '';
        if (item) {
          html += '<div class="layui-form-item" id="' + sign + '-form-tool"><label class="layui-form-label"></label><div class="layui-input-inline">';
          $.each(admin.filterList(page, $.extend(where, {
            ParentID: item.PageID,
            PageType: 'formAction'
          })), function (idx, data) {
            html += '<button class="layui-btn layuiadmin-btn-admin" type="button" lay-event="' + data.Sign + '">' + data['PageName' + admin.lang] + '</button> ';

          });
          html += '<input type="button" lay-submit lay-filter="' + sign + '-form-submit" value="" class="layui-btn layui-btn-default layui-hide">';
          html += '</div></div>';
        }
        return html;
      },
      addHideWhere: function (tableId, name, value, compare, condition) {
        var form = $('#' + tableId + '-search-form');
        if (form.length > 0) {
          if (form.find('[name="' + name + '"]').length > 0) {
            var item = form.find('[name="' + name + '"]');
            item.attr('name', name).val(value);
            if (compare)
              item.attr('compare', compare);
            if (condition)
              item.attr('condition', condition);
          } else {
            form.children().first().prepend('<input type="hidden" name="' + name + '"' + (condition ? (' condition="' + condition + '"') : '') + (compare ? (' compare="' + compare + '"') : '') + ' value="' + value + '" />');
          }
        } else {
          var html = '<form class="layui-form layui-card-header layuiadmin-card-header-auto" nosearchbtn id="' + tableId + '-search-form">';
          html += '<div class="layui-form-item">';
          html += '<input type="hidden" name="' + name + '"' + (condition ? (' condition="' + condition + '"') : '') + (compare ? (' compare="' + compare + '"') : '') + ' value="' + value + '" />';
          html += '</div>';
          html += '</form>';
          $('#' + tableId + '-table').parent().before(html);
        }
      },
      removeHideWhere: function (tableId, name) {
        var form = $('#' + tableId + '-search-form');
        if (form.length > 0) {
          if (form.find('[name="' + name + '"]').length > 0) {
            form.find('[name="' + name + '"]').remove();
          }
        }
      },
      getSearchWhere: function (tableId) {
          var fields = {};
          var formDate = $('#' + tableId + '-search-form').serializeArray();
          console.log("formDate", formDate);
          $.each(formDate, function () {
            fields[this.name] = this.value;
          });

          var searchWhere = [];
          $.each(fields, function (k, v) {
            //if (!v) {
            //    delete fields[k];
            //    return;
            //}
            console.log("0", k);
            console.log("1", $('#' + tableId + '-search-form [name="' + k + '"]').attr('compare'));
            console.log("2", v);
            console.log("3", $('#' + tableId + '-search-form [name="' + k + '"]').attr('condition') === 'null');
            if ($('#' + tableId + '-search-form [name="' + k + '"]').attr('compare') && v || $('#' + tableId + '-search-form [name="' + k + '"]').attr('condition') === 'null')
              searchWhere.push({
                searchValue: v, //admin.trimAll(v),
                condition: $('#' + tableId + '-search-form [name="' + k + '"]').attr('condition'),
                compare: $('#' + tableId + '-search-form [name="' + k + '"]').attr('compare')
              });
          });
          return {
            SearchWhere: searchWhere.length > 0 ? JSON.stringify(searchWhere) : null
          };
        }

        ,
      getFormHtml: function (json) {
          var html = '';
          var isArry = $.isArray(json);
          if (!isArry) {
            if (!admin.hasObject(json)) return;
            var tag = '',
              type = '';
            var child;
            $.each(json, function (k, v) {
              if ($.isArray(v)) {
                child = v;
                return;
              }

              if ($.isPlainObject(v)) return;

              if (k === 'tag') {
                tag = v;
                html += '<' + tag;
              } else if (k === 'itemId') {
                if (v === '') {
                  v = admin.uuid(10, 10);
                  json[k] = v;
                }
                html += ' reitemid="' + v + '"';
              } else {
                html += ' ' + k + '="' + v + '"';
              }
            });
            html += '>';
            if (child && child.length > 0) {
              html += admin.getFormHtml(child);
            }
            html += '</' + tag + '>';

          } else {
            $.each(json, function (idx, data) {
              if (!admin.hasObject(data)) return;
              html += admin.getFormHtml(data);
            });
          }
          return html;
        }

        ,
      getFormTitle: function (table, btn, type) {
        var formTitle = [];
        var tableObj = admin.filterList(admin.getSessionList('page'), {
          Sign: table
        })[0];
        if (tableObj) {
          formTitle.push(tableObj['PageName' + admin.lang]);
          var btnObj = admin.filterList(admin.getSessionList('page'), {
            ParentID: tableObj.PageID,
            Sign: btn,
            PageType: type
          })[0];
          if (btnObj)
            formTitle.push(btnObj['PageName' + admin.lang]);
        }
        return formTitle.join(' - ');
      },
      getFormActionTitle: function (table, btn) {
        return admin.getFormTitle(table, btn, 'formAction');
      },
      getToolFormTitle: function (table, btn) {
        return admin.getFormTitle(table, btn, 'action');
      },
      getToolbarFormTitle: function (table, btn) {
          return admin.getFormTitle(table, btn, 'cellAction');
        }

        ,
      setFormSelectTitleLang: function (formid, filedName) {
        return admin.getDictionary('page-form-field', formid, function (d) {
          var field = admin.filterList(admin.getSessionList('page-form-field-' + formid), {
            Member: filedName
          })[0];
          return field ? field['MemberName' + admin.lang] : '';
        });
      },
      setFormSelectLang: function (formid, filedName) {
          return admin.getDictionary('page-form-field', formid, function (d) {
            var field = admin.filterList(d, {
              Member: filedName
            })[0];
            return field ? (admin.lang ? 'Please select ' : '请选择') + field['MemberName' + admin.lang] : '';
          });
        }

        //事件监听
        ,
      on: function (events, callback) {
          return layui.onevent.call(this, setter.MOD_NAME, events, callback);
        }

        //弹出面板
        ,
      popup: view.popup

        //右侧面板
        ,
      popupRight: function (options) {
          //layer.close(admin.popup.index);
          return admin.popup.index = layer.open($.extend({
            type: 1,
            id: 'LAY_adminPopupR',
            anim: -1,
            title: false,
            closeBtn: false,
            offset: 'r',
            shade: 0.1,
            shadeClose: true,
            skin: 'layui-anim layui-anim-rl layui-layer-adminRight',
            area: '300px'
          }, options));
        }

        //屏幕类型
        ,
      screen: function () {
          var width = $win.width();
          if (width > 1200) {
            return 3; //大屏幕
          } else if (width > 992) {
            return 2; //中屏幕
          } else if (width > 768) {
            return 1; //小屏幕
          } else {
            return 0; //超小屏幕
          }
        }

        //侧边伸缩
        ,
      sideFlexible: function (status) {
          var app = container,
            iconElem = $('#' + APP_FLEXIBLE),
            screen = admin.screen();

          //设置状态，PC：默认展开、移动：默认收缩
          if (status === 'spread') {
            //切换到展开状态的 icon，箭头：←
            iconElem.removeClass(ICON_SPREAD).addClass(ICON_SHRINK);

            //移动：从左到右位移；PC：清除多余选择器恢复默认
            if (screen < 2) {
              app.addClass(APP_SPREAD_SM);
            } else {
              app.removeClass(APP_SPREAD_SM);
            }

            app.removeClass(SIDE_SHRINK)
          } else {
            //切换到搜索状态的 icon，箭头：→
            iconElem.removeClass(ICON_SHRINK).addClass(ICON_SPREAD);

            //移动：清除多余选择器恢复默认；PC：从右往左收缩
            if (screen < 2) {
              app.removeClass(SIDE_SHRINK);
            } else {
              app.addClass(SIDE_SHRINK);
            }

            app.removeClass(APP_SPREAD_SM)
          }

          layui.event.call(this, setter.MOD_NAME, 'side({*})', {
            status: status
          });
        }

        //重置主体区域表格尺寸
        ,
      resizeTable: function (delay) {
          var that = this,
            runResizeTable = function () {
              that.tabsBody(admin.tabsPage.index).find('.layui-table-view').each(function () {
                var tableID = $(this).attr('lay-id');
                layui.table.resize(tableID);
              });
            };
          if (!layui.table) return;
          delay ? setTimeout(runResizeTable, delay) : runResizeTable();
        }

        //主题设置
        ,
      theme: function (options) {
          var theme = setter.theme,
            local = layui.data(setter.tableName),
            id = 'LAY_layadmin_theme',
            style = document.createElement('style'),
            styleText = laytpl([
              //主题色
              '.layui-side-menu,', '.layadmin-pagetabs .layui-tab-title li:after,', '.layadmin-pagetabs .layui-tab-title li.layui-this:after,', '.layui-layer-admin .layui-layer-title,', '.layadmin-side-shrink .layui-side-menu .layui-nav>.layui-nav-item>.layui-nav-child', '{background-color:{{d.color.main}} !important;}'

              , '.layui-btn-default,.layui-layer-admin .layui-layer-title,.layui-layer-title{color: d.color.selected;background-color:{{d.color.header}} !important;}'

              //选中色
              , '.layui-nav-tree .layui-this,', '.layui-nav-tree .layui-this>a,', '.layui-nav-tree .layui-nav-child dd.layui-this,', '.layui-nav-tree .layui-nav-child dd.layui-this a', '{background-color:{{d.color.selected}} !important;}'

              //logo
              , '.layui-layout-admin .layui-logo{background-color:{{d.color.logo || d.color.main}} !important;}'

              //头部色
              , '{{# if(d.color.header){ }}', '.layui-layout-admin .layui-header{background-color:{{ d.color.header }};}', '.layui-layout-admin .layui-header a,', '.layui-layout-admin .layui-header a cite{color: #f8f8f8;}', '.layui-layout-admin .layui-header a:hover{color: #fff;}', '.layui-layout-admin .layui-header .layui-nav .layui-nav-more{border-top-color: #fbfbfb;}', '.layui-layout-admin .layui-header .layui-nav .layui-nav-mored{border-color: transparent; border-bottom-color: #fbfbfb;}', '.layui-layout-admin .layui-header .layui-nav .layui-this:after, .layui-layout-admin .layui-header .layui-nav-bar{background-color: #fff; background-color: rgba(255,255,255,.5);}', '.layadmin-pagetabs .layui-tab-title li:after{display: none;}', '{{# } }}'
            ].join('')).render(options = $.extend({}, local.theme, options)),
            styleElem = document.getElementById(id);

          //添加主题样式
          if ('styleSheet' in style) {
            style.setAttribute('type', 'text/css');
            style.styleSheet.cssText = styleText;
          } else {
            style.innerHTML = styleText;
          }
          style.id = id;

          styleElem && $body[0].removeChild(styleElem);
          $body[0].appendChild(style);
          $body.attr('layadmin-themealias', options.color.alias);

          //本地存储记录
          local.theme = local.theme || {};
          layui.each(options, function (key, value) {
            local.theme[key] = value;
          });
          layui.data(setter.tableName, {
            key: 'theme',
            value: local.theme
          });
        }

        //初始化主题
        ,
      initTheme: function (index) {
          var theme = setter.theme;
          index = index || 0;
          if (theme.color[index]) {
            theme.color[index].index = index;
            admin.theme({
              color: theme.color[index]
            });
          }
        }

        //语言设置
        ,
      language: function (options) {
          var local = layui.data(setter.tableName);

          local.language = local.language || {};

          layui.each(options, function (key, value) {
            local.language[key] = value;
          });
          //更改语言修改 
          local.language = '';
          layui.data(setter.tableName, {
            key: 'language',
            value: local.language
          });
        }

        //初始化主题
        ,
      initLanguage: function (lang) {
          admin.language({
            lang: lang,
            v: admin.v
          });
        }

        //记录最近一次点击的页面标签数据
        ,
      tabsPage: {}

      //获取标签页的头元素
      ,
      tabsHeader: function (index) {
          return $('#LAY_app_tabsheader').children('li').eq(index || 0);
        }

        //获取页面标签主体元素
        ,
      tabsBody: function (index) {
          return $(APP_BODY).find('.' + TABS_BODY).eq(index || 0);
        }

        //切换页面标签主体
        ,
      tabsBodyChange: function (index) {
          admin.tabsHeader(index).attr('lay-attr', layui.router().href);
          admin.tabsBody(index).addClass(SHOW).siblings().removeClass(SHOW);
          events.rollPage('auto', index);
        }

        ,
      sideThis: function () {
          //$('#LAY-system-side-menu .layui-this').closest('dl').addClass('layui-nav-itemed');
          //$('#LAY-system-side-menu .layui-this').closest('li').addClass('layui-nav-itemed');

          $('#LAY-system-side-menu .layui-this').closest('.layui-nav-item').addClass('layui-nav-itemed').siblings().removeClass('layui-nav-itemed');
          $('#LAY-system-side-menu .layui-this').closest('dl.layui-nav-child').addClass('layui-nav-itemed').siblings().removeClass('layui-nav-itemed');
        }

        //resize事件管理
        ,
      resize: function (fn) {
        var router = layui.router(),
          key = router.path.join('-');

        if (admin.resizeFn[key]) {
          $win.off('resize', admin.resizeFn[key]);
          delete admin.resizeFn[key];
        }

        if (fn === 'off') return; //如果是清除 resize 事件，则终止往下执行

        fn(), admin.resizeFn[key] = fn;
        $win.on('resize', admin.resizeFn[key]);
      },
      resizeFn: {},
      runResize: function () {
        var router = layui.router(),
          key = router.path.join('-');
        admin.resizeFn[key] && admin.resizeFn[key]();
      },
      delResize: function () {
          this.resize('off');
        }

        //关闭当前 pageTabs
        ,
      closeThisTabs: function () {
          if (!admin.tabsPage.index) return;
          $(TABS_HEADER).eq(admin.tabsPage.index).find('.layui-tab-close').trigger('click');
        }

        //全屏
        ,
      fullScreen: function () {
          var ele = document.documentElement,
            reqFullScreen = ele.requestFullScreen || ele.webkitRequestFullScreen ||
            ele.mozRequestFullScreen || ele.msRequestFullscreen;
          if (typeof reqFullScreen !== 'undefined' && reqFullScreen) {
            reqFullScreen.call(ele);
          }
        }

        //退出全屏
        ,
      exitScreen: function () {
          var ele = document.documentElement;
          if (document.exitFullscreen) {
            document.exitFullscreen();
          } else if (document.mozCancelFullScreen) {
            document.mozCancelFullScreen();
          } else if (document.webkitCancelFullScreen) {
            document.webkitCancelFullScreen();
          } else if (document.msExitFullscreen) {
            document.msExitFullscreen();
          }
        }

        //纠正单页路由格式
        ,
      correctRouter: function (href) {
        if (!/^\//.test(href)) href = '/' + href;

        //纠正首尾
        return href.replace(/^(\/+)/, '/')
          .replace(new RegExp('\/' + setter.entry + '$'), '/'); //过滤路由最后的默认视图文件名（如：index）
      }

      //……
    };

  //事件
  var events = admin.events = {
    logout: function () {
        //执行退出接口
        admin.req({
          url: '/Account/SignOut',
          type: 'post',
          data: {},
          done: function (res) { //这里要说明一下：done 是只有 response 的 code 正常才会执行。而 succese 则是只要 http 为 200 就会执行

            //清空本地记录的 token，并跳转到登入页
            debugger
            admin.exit();
          }
        });
      }

      //伸缩
      ,
    flexible: function (othis) {
        var iconElem = othis.find('#' + APP_FLEXIBLE),
          isSpread = iconElem.hasClass(ICON_SPREAD);
        admin.sideFlexible(isSpread ? 'spread' : null); //控制伸缩
        admin.resizeTable(350);
      }

      //刷新
      ,
    refresh: function () {
        layui.index.render();
      }

      //输入框搜索
      ,
    serach: function (othis) {
        othis.off('keypress').on('keypress', function (e) {
          if (!this.value.replace(/\s/g, '')) return;
          //回车跳转
          if (e.keyCode === 13) {
            var href = othis.attr('lay-action'),
              text = othis.attr('lay-text') || '搜索';

            href = href + this.value;
            text = text + ' <span style="color: #FF5722;">' + admin.escape(this.value) + '</span>';

            //打开标签页
            location.hash = admin.correctRouter(href);

            //如果搜索关键词已经打开，则刷新页面即可
            events.serach.keys || (events.serach.keys = {});
            events.serach.keys[admin.tabsPage.index] = this.value;
            if (this.value === events.serach.keys[admin.tabsPage.index]) {
              events.refresh(othis);
            }

            //清空输入框
            this.value = '';
          }
        });
      }

      //点击消息
      ,
    message: function (othis) {
        othis.find('.layui-badge-dot').remove();
      }

      //弹出主题面板
      ,
    theme: function () {
        admin.popupRight({
          id: 'LAY_adminPopupTheme',
          success: function () {
            view(this.id).render('admin/tpl/theme');
          }
        });
      }

      //便签
      ,
    note: function (othis) {
        var mobile = admin.screen() < 2,
          note = layui.data(setter.tableName).note;

        events.note.index = admin.popup({
          title: '便签',
          shade: 0,
          offset: [
            '41px', (mobile ? null : (othis.offset().left - 250) + 'px')
          ],
          anim: -1,
          id: 'LAY_adminNote',
          skin: 'layadmin-note layui-anim layui-anim-upbit',
          content: '<textarea placeholder="内容"></textarea>',
          resize: false,
          success: function (layero, index) {
            var textarea = layero.find('textarea'),
              value = note === undefined ? '便签中的内容会存储在本地，这样即便你关掉了浏览器，在下次打开时，依然会读取到上一次的记录。是个非常小巧实用的本地备忘录' : note;

            textarea.val(value).focus().on('keyup', function () {
              layui.data(setter.tableName, {
                key: 'note',
                value: this.value
              });
            });
          }
        });
      }

      //全屏
      ,
    fullscreen: function (othis) {
        var SCREEN_FULL = 'layui-icon-screen-full',
          SCREEN_REST = 'layui-icon-screen-restore',
          iconElem = othis.children("i");

        if (iconElem.hasClass(SCREEN_FULL)) {
          admin.fullScreen();
          iconElem.addClass(SCREEN_REST).removeClass(SCREEN_FULL);
        } else {
          admin.exitScreen();
          iconElem.addClass(SCREEN_FULL).removeClass(SCREEN_REST);
        }
      }

      //弹出关于面板
      ,
    about: function () {
        admin.popupRight({
          id: 'LAY_adminPopupAbout',
          success: function () {
            view(this.id).render('system/about');
          }
        });
      }

      //弹出更多面板
      ,
    more: function () {
        admin.popupRight({
          id: 'LAY_adminPopupMore',
          success: function () {
            view(this.id).render('system/more');
          }
        });
      }

      //返回上一页
      ,
    back: function () {
        history.back();
      }

      //主题设置
      ,
    setTheme: function (othis) {
        var index = othis.data('index'),
          nextIndex = othis.siblings('.layui-this').data('index');

        if (othis.hasClass(THIS)) return;

        othis.addClass(THIS).siblings('.layui-this').removeClass(THIS);
        admin.initTheme(index);
      }

      //语言设置
      ,
    setLanguage: function (othis) {
        admin.initLanguage(othis.data('lang'));
        location.href = '/';
      }

      //左右滚动页面标签
      ,
    rollPage: function (type, index) {
        var tabsHeader = $('#LAY_app_tabsheader'),
          liItem = tabsHeader.children('li'),
          scrollWidth = tabsHeader.prop('scrollWidth'),
          outerWidth = tabsHeader.outerWidth(),
          tabsLeft = parseFloat(tabsHeader.css('left'));

        //右左往右
        if (type === 'left') {
          if (!tabsLeft && tabsLeft <= 0) return;

          //当前的left减去可视宽度，用于与上一轮的页标比较
          var prefLeft = -tabsLeft - outerWidth;

          liItem.each(function (index, item) {
            var li = $(item),
              left = li.position().left;

            if (left >= prefLeft) {
              tabsHeader.css('left', -left);
              return false;
            }
          });
        } else if (type === 'auto') { //自动滚动
          (function () {
            var thisLi = liItem.eq(index),
              thisLeft;

            if (!thisLi[0]) return;
            thisLeft = thisLi.position().left;

            //当目标标签在可视区域左侧时
            if (thisLeft < -tabsLeft) {
              return tabsHeader.css('left', -thisLeft);
            }

            //当目标标签在可视区域右侧时
            if (thisLeft + thisLi.outerWidth() >= outerWidth - tabsLeft) {
              var subLeft = thisLeft + thisLi.outerWidth() - (outerWidth - tabsLeft);
              liItem.each(function (i, item) {
                var li = $(item),
                  left = li.position().left;

                //从当前可视区域的最左第二个节点遍历，如果减去最左节点的差 > 目标在右侧不可见的宽度，则将该节点放置可视区域最左
                if (left + tabsLeft > 0) {
                  if (left - tabsLeft > subLeft) {
                    tabsHeader.css('left', -left);
                    return false;
                  }
                }
              });
            }
          }());
        } else {
          //默认向左滚动
          liItem.each(function (i, item) {
            var li = $(item),
              left = li.position().left;

            if (left + li.outerWidth() >= outerWidth - tabsLeft) {
              tabsHeader.css('left', -left);
              return false;
            }
          });
        }
      }

      //向右滚动页面标签
      ,
    leftPage: function () {
        events.rollPage('left');
      }

      //向左滚动页面标签
      ,
    rightPage: function () {
        events.rollPage();
      }

      //关闭当前标签页
      ,
    closeThisTabs: function () {
        admin.closeThisTabs();
      }

      //关闭其它标签页
      ,
    closeOtherTabs: function (type) {
        var TABS_REMOVE = 'LAY-system-pagetabs-remove';
        if (type === 'all') {
          $(TABS_HEADER + ':gt(0)').remove();
          $(APP_BODY).find('.' + TABS_BODY + ':gt(0)').remove();
        } else {
          $(TABS_HEADER).each(function (index, item) {
            if (index && index !== admin.tabsPage.index) {
              $(item).addClass(TABS_REMOVE);
              admin.tabsBody(index).addClass(TABS_REMOVE);
            }
          });
          $('.' + TABS_REMOVE).remove();
        }
      }

      //关闭全部标签页
      ,
    closeAllTabs: function () {
        events.closeOtherTabs('all');
        location.hash = '';
      }

      //遮罩
      ,
    shade: function () {
      admin.sideFlexible();
    }
  };

  //初始
  ! function () {
    //主题初始化，本地主题记录优先，其次为 initColorIndex
    var local = layui.data(setter.tableName);
    console.log("local", local)
    if (local.theme) {
      admin.theme(local.theme);
    } else if (setter.theme) {
      admin.initTheme(setter.theme.initColorIndex);
    }

    if (local.language) {
      admin.language(local.language);
    } else
      admin.initLanguage(setter.lang || '');


    //禁止水平滚动
    $body.addClass('layui-layout-body');

    //移动端强制不开启页面标签功能
    if (admin.screen() < 1) {
      delete setter.pageTabs;
    }

    //不开启页面标签时
    if (!setter.pageTabs) {
      container.addClass('layadmin-tabspage-none');
    }

    //低版本IE提示
    if (device.ie && device.ie < 10) {
      view.error('IE' + device.ie + '下访问可能不佳，推荐使用：Chrome / Firefox / Edge 等高级浏览器', {
        offset: 'auto',
        id: 'LAY_errorIE'
      });
    }

  }();

  //admin.prevRouter = {}; //上一个路由

  //监听 hash 改变侧边状态
  admin.on('hash(side)', function (router) {

    var path = router.path,
      getData = function (item) {
        return {
          list: item.children('.layui-nav-child'),
          name: item.data('name'),
          jump: item.data('jump')
        };
      },
      sideMenu = $('#' + SIDE_MENU),
      SIDE_NAV_ITEMD = 'layui-nav-itemed'

      //捕获对应菜单
      ,
      matchMenu = function (list) {
        var pathURL = admin.correctRouter(path.join('/'));

        pathURL = $.inArray(pathURL, layui.setter.templatePage) > -1 ? (pathURL + '/pageId=' + layui.router().search.pageId) : pathURL;

        list.each(function (index1, item1) {
          var othis1 = $(item1),
            data1 = getData(othis1),
            listChildren1 = data1.list.children('dd'),
            matched1 = path[0] === data1.name || index1 === 0 && !path[0] ||
            data1.jump && pathURL === admin.correctRouter(data1.jump);

          listChildren1.each(function (index2, item2) {
            var othis2 = $(item2),
              data2 = getData(othis2),
              listChildren2 = data2.list.children('dd'),
              matched2 = path[0] === data1.name && path[1] === data2.name ||
              data2.jump && pathURL === admin.correctRouter(data2.jump);

            listChildren2.each(function (index3, item3) {
              var othis3 = $(item3),
                data3 = getData(othis3),
                matched3 = path[0] === data1.name && path[1] === data2.name && path[2] === data3.name ||
                data3.jump && pathURL === admin.correctRouter(data3.jump);

              if (matched3) {
                var selected = data3.list[0] ? SIDE_NAV_ITEMD : THIS;
                othis3.addClass(selected).siblings().removeClass(selected); //标记选择器
                admin.sideThis();
                return false;
              }

            });

            if (matched2) {
              var selected = data2.list[0] ? SIDE_NAV_ITEMD : THIS;
              othis2.addClass(selected).siblings().removeClass(selected); //标记选择器
              admin.sideThis();
              return false;
            }

          });

          if (matched1) {
            var selected = data1.list[0] ? SIDE_NAV_ITEMD : THIS;
            othis1.addClass(selected).siblings().removeClass(selected); //标记选择器
            admin.sideThis();
            return false;
          }

        });
      };

    //重置状态
    sideMenu.find('.' + THIS).removeClass(THIS);

    //移动端点击菜单时自动收缩
    if (admin.screen() < 2) admin.sideFlexible();

    //开始捕获
    matchMenu(sideMenu.children('li'));
  });

  //监听侧边导航点击事件
  element.on('nav(layadmin-system-side-menu)', function (elem) {
    if (elem.siblings('.layui-nav-child')[0] && container.hasClass(SIDE_SHRINK)) {
      admin.sideFlexible('spread');
      layer.close(elem.data('index'));
    }
    admin.tabsPage.type = 'nav';
  });

  //监听选项卡的更多操作
  element.on('nav(layadmin-pagetabs-nav)', function (elem) {
    var dd = elem.parent();
    dd.removeClass(THIS);
    dd.parent().removeClass(SHOW);
  });

  //同步路由
  var setThisRouter = function (othis) {
      var layid = othis.attr('lay-id'),
        attr = othis.attr('lay-attr'),
        index = othis.index();

      location.hash = layid === setter.entry ? '/' : (attr || '/');
      admin.tabsBodyChange(index);
    },
    TABS_HEADER = '#LAY_app_tabsheader>li';

  //页面标签点击
  $body.on('click', TABS_HEADER, function () {
    var othis = $(this),
      index = othis.index();

    admin.tabsPage.type = 'tab';
    admin.tabsPage.index = index;
    //如果是iframe类型的标签页
    if (othis.attr('lay-attr') === 'iframe') {
      return admin.tabsBodyChange(index);
    }


    setThisRouter(othis); //同步路由
    admin.runResize(); //执行resize事件，如果存在的话
    admin.resizeTable(); //重置当前主体区域的表格尺寸
  });

  //监听 tabspage 删除
  element.on('tabDelete(layadmin-layout-tabs)', function (obj) {
    var othis = $(TABS_HEADER + '.layui-this');

    admin.tabsPage.type = 'tab';

    obj.index && admin.tabsBody(obj.index).remove();
    setThisRouter(othis);

    //移除resize事件
    admin.delResize();
  });

  //页面跳转
  $body.on('click', '*[lay-href]', function () {
    var othis = $(this),
      href = othis.attr('lay-href'),
      router = layui.router();

    admin.tabsPage.elem = othis;
    //admin.prevRouter[router.path[0]] = router.href; //记录上一次各菜单的路由信息

    //执行跳转
    location.hash = admin.correctRouter(href);
  });

  //点击事件
  $body.on('click', '*[layadmin-event]', function () {
    var othis = $(this),
      attrEvent = othis.attr('layadmin-event');
    events[attrEvent] && events[attrEvent].call(this, othis);
  });

  //tips
  $body.on('mouseenter', '*[lay-tips]', function () {
    var othis = $(this);

    if (othis.parent().hasClass('layui-nav-item') && !container.hasClass(SIDE_SHRINK)) return;

    var tips = othis.attr('lay-tips'),
      offset = othis.attr('lay-offset'),
      direction = othis.attr('lay-direction'),
      index = layer.tips(tips, this, {
        tips: direction || 1,
        time: -1,
        success: function (layero, index) {
          if (offset) {
            layero.css('margin-left', offset + 'px');
          }
        }
      });
    othis.data('index', index);
  }).on('mouseleave', '*[lay-tips]', function () {
    layer.close($(this).data('index'));
  });

  //窗口resize事件
  var resizeSystem = layui.data.resizeSystem = function () {
    //layer.close(events.note.index);
    layer.closeAll('tips');

    if (!resizeSystem.lock) {
      setTimeout(function () {
        admin.sideFlexible(admin.screen() < 2 ? '' : 'spread');
        delete resizeSystem.lock;
      }, 100);
    }

    resizeSystem.lock = true;
  };
  $win.on('resize', layui.data.resizeSystem);

  //接口输出
  exports('admin', admin);
});